/* Copyright (C) 2008  Romolo Camplani, Marco Fortunato, Marco Marelli, Guido Rota, Fabio A. Schreiber et al.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.dei.perla.rockfall.utils;

import org.dei.perla.sys.device.fpc.dspic.DSPicFPC;

public class PopulateDB {
	
	private static final int FPC_NUMBER = 2;
	private static final int ITERATION_NUMBER = 20;
	
	public static void main(String[] args) {	
		int fpcNum = FPC_NUMBER;
		int iterationNum = ITERATION_NUMBER;
		System.out.println("Setting up...");
		if(args.length == 2){
			fpcNum = Integer.parseInt(args[0]);
			iterationNum = Integer.parseInt(args[1]);
		}
		
		TimeElapsed.setCapacity(fpcNum * iterationNum);
		new Thread(new MemoryMonitor(500)).start();
		new Thread(new Synchronizer(fpcNum)).start();
		
		DSPicFPC fpc;
		DSPicDataGeneratorThread gen;
		for (int i = 0; i < fpcNum; i ++) {
			gen = new DSPicDataGeneratorThread(iterationNum);
			fpc = new DSPicFPC(gen.getCommunicationPipes(), i * iterationNum);
			new Thread(new DatabaseDump(fpc.registerQuery(null))).start();
			new Thread(gen).start();
		}
	}
}

class MemoryMonitor implements Runnable{
	private int sampleTime;
	private long totalMemory;
	private long freeMemory;
	private long maxMemory;
	
	public MemoryMonitor(int sampletime) {
		sampleTime = sampletime;
		Runtime.getRuntime().gc();
		maxMemory = Runtime.getRuntime().maxMemory();
		freeMemory = Runtime.getRuntime().freeMemory();
		totalMemory = Runtime.getRuntime().totalMemory();
		long memoryUsed = totalMemory - freeMemory;
		double percentMemoryUsed = ((double)(memoryUsed) / (double)maxMemory)*100.0;
		System.out.println("[MEM] max available memory (bytes)" + maxMemory);
		System.out.println("[MEM] used " + memoryUsed + " %" + percentMemoryUsed);
	}
	
	public void run() {
		long memoryUsed;
		double percentMemoryUsed;
		while(true){
			freeMemory = Runtime.getRuntime().freeMemory();
			totalMemory = Runtime.getRuntime().totalMemory();
			memoryUsed = totalMemory - freeMemory;
			percentMemoryUsed = ((double)(memoryUsed) / (double)maxMemory)*100.0;
			
			System.out.println("[MEM] used " + memoryUsed + " %" + percentMemoryUsed);
			try {
				Thread.sleep(sampleTime);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}	
}
